<template>
  <view class="container"
        @touchstart="onTouchStart"
        @touchend="onTouchEnd"
  >
    <!-- ① 抽屉侧边栏 -->
    <uni-drawer
        ref="drawer"
        mode="left"
        :width="drawerWidth"
        :mask-click="true"
        @change="onDrawerChange"
        class="drawer-panel"
    >
      <view class="drawer-content">
        <scroll-view scroll-y class="page-list">
          <view
              v-for="page in pagesList"
              :key="page.pageId"
              class="page-item"
              @tap="selectPage(page.pageUrl)"
          >
            {{ page.pageName }}
          </view>
        </scroll-view>
      </view>
    </uni-drawer>

    <!-- ② WebView 区域 -->
    <view class="webview-container">
      <web-view
          v-if="currentUrl && !isDrawerOpen"
          id="subWebview"
          :src="currentUrl"
          :webview-styles="webviewStyles"
          :data="{ backButtonAutoControl:'hide' }"
          class="webview"
          @loading="onLoading"
          @loaded="onLoaded"
          @loaderror="onLoadError"
      />
    </view>

    <!-- ③ 加载 / 错误提示 -->
<!--    <view class="loading-container" v-if="isLoading">-->
<!--      <uni-icons custom-prefix="iconfont" type="spinner-cycle" size="24" :animation="true" />-->
<!--      <text class="loading-text">加载中...</text>-->
<!--    </view>-->

<!--    <view class="error-container" v-if="hasError">-->
<!--      <uni-icons type="error" size="40" />-->
<!--      <text class="error-text">{{ errorMessage }}</text>-->
<!--      <view class="retry-button" @tap="reloadWebView">重试</view>-->
<!--    </view>-->
  </view>
</template>

<script setup lang="ts">
import { ref, computed, nextTick, onMounted } from 'vue'
import { onBackPress, onShow } from '@dcloudio/uni-app'
import { getMessageCount, getPageList } from '@/api/app/user'
import UniDrawer from "@/uni_modules/uni-drawer/components/uni-drawer/uni-drawer.vue"

const drawerWidth    = '100%'
const drawer         = ref<InstanceType<typeof UniDrawer> | null>(null)
const isDrawerOpen   = ref(false)
const pagesList      = ref<{ pageId: number; pageName: string; pageUrl: string }[]>([])
const currentUrl     = ref<string>('')
const isLoading      = ref(false)
const hasError       = ref(false)
const errorMessage   = ref('')
const statusBarHeight= ref(0)

// ↓ 把这里从 80 改成 60 ↓
const TOOLBAR_RPX    = 0
const toolbarPx      = computed(() => uni.upx2px(TOOLBAR_RPX))
const webviewStyles  = ref({
  top : '0px',
  bottom: '0px',
  progress:{ color:'#2979ff' },
  scrollIndicator:'none',
  disableScroll: true
})

async function fetchPages() {
  try {
    const { code, data } = await getPageList()
    if (code === 200) pagesList.value = data
  } catch {}
}

function openDrawer() {
  drawer.value?.open()
  isDrawerOpen.value = true
}

function closeDrawer() {
  drawer.value?.close()
  isDrawerOpen.value = false
}

function onDrawerChange(e: { show: boolean }) {
  isDrawerOpen.value = e.show
}

function selectPage(url: string) {
  currentUrl.value = url
  isLoading.value  = true
  hasError.value   = false
  closeDrawer()
}

function onLoading() {
  isLoading.value = true
  hasError.value  = false
}
function onLoaded() {
  isLoading.value = false
}
function onLoadError() {
  isLoading.value   = false
  hasError.value    = true
  errorMessage.value = '页面加载失败，请检查网络'
}
function reloadWebView() {
  const url = currentUrl.value
  currentUrl.value = ''
  nextTick(() => {
    currentUrl.value = url
    isLoading.value  = true
    hasError.value   = false
  })
}

onBackPress(() => {
  if (isDrawerOpen.value) closeDrawer()
  else                    openDrawer()
  return true
})

let timer: ReturnType<typeof setInterval> | null = null
function startTimer() {
  timer = setInterval(async () => {
    const { data: count } = await getMessageCount()
    if (count > 0) uni.setTabBarBadge({ index: 1, text: String(count) })
    else           uni.removeTabBarBadge({ index: 1 })
  }, 3000)
}

onMounted(async () => {
  statusBarHeight.value = uni.getSystemInfoSync().statusBarHeight || 0
  // ↓ 顶部偏移也会自动变小 ↓
  webviewStyles.value.top = statusBarHeight.value + toolbarPx.value + 'px'

  await fetchPages()
  setTimeout(openDrawer, 200)
  startTimer()
})

onShow(() => {
  uni.removeTabBarBadge({ index: 1 })
  timer && clearInterval(timer)
  startTimer()
})
</script>

<style>
.container           { position:relative; width:100%; height:100%; overflow:hidden; padding-top:env(safe-area-inset-top); }
/* Drawer */
.drawer-panel        { position:absolute; top:0; left:0; width:70%; height:100%; z-index:2000; }
.drawer-content      { background:#fff; height:100%; padding-top:20rpx; }
.page-list           { height:100%; }
.page-item           { padding:30rpx 40rpx; font-size:28rpx; border-bottom:1px solid #f0f0f0; }
/* WebView */
.webview-container   { position:absolute; top:0; left:0; right:0; bottom:0; z-index:0; }
.webview             { width:100%; height:100%; }
/* Loading / Error */
.loading-container,
.error-container     { position:fixed; top:50%; left:50%; transform:translate(-50%,-50%); display:flex; flex-direction:column; align-items:center; z-index:3000; }
.loading-text,
.error-text          { margin-top:20rpx; font-size:14px; color:#666; }
.retry-button        { margin-top:30rpx; padding:20rpx 60rpx; background:#2979ff; color:#fff; border-radius:8rpx; font-size:14px; }
</style>
